import java.io.Console;
import java.io.IOException;
import java.io.Reader;
import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.sql.*;
import java.util.Properties;

// Class to handle user login

public class UserLogin {
	
	// Is the user logged in?
	static boolean loggedIn = false;
	// What is the user ID? Default = 0
	static int userID = 0;

	// Login
	// Gives user 3 tries	
	public static boolean login() throws ClassNotFoundException,SQLException,IOException, NoSuchAlgorithmException {
		Console console = System.console();
		
		// variables
		boolean validLogin = false;
		int tries = 0;
		String username = null;
		String password = null;
		
		// Login loop
		while (!validLogin && tries < 3) {

			// Read in username and password
			username = console.readLine("\nusername: ");
			password = new String(console.readPassword("password: "));
			
			// Create connection
			Connection c = mysqlConnection.connect();
		
			// Does the username exist?
			PreparedStatement s1 = c.prepareStatement("SELECT Salt FROM User WHERE Username=?");
			s1.setString(1,username);
			ResultSet rSalt = s1.executeQuery();
			Reader salt = null;

			// User exists, get salt for password
			if (rSalt.next()) {
				salt = rSalt.getCharacterStream("salt");
			}
			// User does not exist
			else {
				validLogin = false;
				System.out.println("\nUsername or password is invalid. Please try again:");
				tries++;
				continue;
			}

			// Append the salt to the password
			char[] saltA = new char[16];
			salt.read(saltA);
			String strSalt = saltA.toString();
			password.concat(strSalt);
			// Hash the salted password
			MessageDigest md = MessageDigest.getInstance("SHA-256");
			md.update(password.getBytes("UTF-8"));
			String saltedHash = new BigInteger(1, md.digest()).toString(16);
			
			// Does the hash match the one in the database?
			PreparedStatement s = c.prepareStatement("SELECT UserID FROM User WHERE Username=? AND Password=?");
			s.setString(1,username);
			s.setString(2, saltedHash);
			ResultSet result = s.executeQuery();
			
			// Yes! Logged in. Keep the user ID available for other programs.
			if (result.next()) {
				userID = result.getInt("UserID");
				validLogin = true;
			}
			// The hashes do not pass. Wrong password.
			else {
				System.out.println("\nUsername or password is invalid. Please try again:");
				tries++;
				continue;
			}
		}
		loggedIn = true;
		return true;
		
	}
	
	public static void main(String[] args) throws ClassNotFoundException,SQLException,IOException,NoSuchAlgorithmException {
		login();
	}
	
}


